<template>
  <div :id="'scrollbox' + KEY" class="scrollbox">
    <div :id="'slideBoxCon' + KEY" class="slideBoxCon" :style="{ top: -range + 'px' }">
      <slot></slot>
      <!-- <slot></slot> -->
    </div>
  </div>
</template>

<script>
export default {
  name: "scrollbox",
  data() {
    return {
      range: 0, //滚动距离
      timer: null,
      timerOut: null //点击菜单关闭定时器,滚动到对应位置,3秒后重新开始滚动
    };
  },
  props: {
    //区分不同的组件引用,防止获取到高度一样情况
    KEY: {
      type: String,
      default: "1"
    },
    //控制滚动速度
    step: {
      type: Number,
      default: 10
    },
    changenum: {
      type: Number,
      default: 0
    },
    itemScroll: {
      type: Number,
      default: 0
    }
  },
  watch: {
    changenum(newVal, oldVal) {
      if (newVal == oldVal || newVal != oldVal) {
        this.range = Math.ceil(
          newVal -
            document.getElementById("slideBoxCon" + this.KEY).offsetHeight / 2
        );
        clearInterval(this.timer);
        clearInterval(this.timerOut);
        this.timerOut = setTimeout(() => {
          this.scrollTop();
        }, 3000);
      }
    }
  },
  // computed: {
  //   step() {
  //     return this.step;
  //   }
  // },
  created() {},
  mounted() {
    //等待数据请求完成
    this.timerOut = setTimeout(() => {
      this.scrollTop();
    }, 6000);
  },
  destroyed() {
    this.timer = null;
    this.timerOut = null;
  },
  methods: {
    scrollTop() {
      console.log(this.step, 8888);
      clearInterval(this.timerOut);
      var boxHeight = document.getElementById("scrollbox" + this.KEY)
        .offsetHeight;
      var itemHeight =
        document.getElementById("slideBoxCon" + this.KEY).offsetHeight + 20;
      this.timer = setInterval(() => {
        if (this.range < Math.ceil(itemHeight - boxHeight)) {
          this.range += this.step / 10;
        } else {
          this.range = 0;
        }
      }, 50);
    }
  }
};
</script>

<style lang="scss" scoped>
.scrollbox {
  margin-top: 0.1rem;
  height: calc(100% - 0.6rem);
  overflow: hidden;
  text-align: center;
  .slideBoxCon {
    position: relative;
    // transition: top 1s;
  }
}
</style>
